package com.jsbj.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsbj.page.PageDomain;
import com.jsbj.page.TableSupport;
import com.jsbj.tools.RequestHeaderUtils;
import com.jsbj.tools.StringUtils;
import com.jsbj.user.entities.SysEqu;
import com.jsbj.user.entities.SysGroup;
import com.jsbj.user.entities.SysUser;
import com.jsbj.user.entities.SysUserGroup;
import com.jsbj.user.mapper.SysGroupMapper;
import com.jsbj.user.service.ISysEquService;
import com.jsbj.user.service.ISysGroupService;
import com.jsbj.user.service.ISysUserGroupService;
import com.jsbj.user.service.ISysUserService;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 群组表
 服务实现类
 * </p>
 *
 * @author jsbj
 * @since 2023-02-06
 */
@Service
public class SysGroupServiceImpl extends ServiceImpl<SysGroupMapper, SysGroup> implements ISysGroupService {

    @Autowired
    private ISysEquService sysEquService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private ISysUserGroupService sysUserGroupService;
    @Autowired
    private ISysUserService sysUserService;

    @Override
    public List<SysGroup> queryGroupByEquNum(String equNum) {
        SysEqu sysEqu= sysEquService.getInfoByEquNum(equNum);
        if(sysEqu==null){
            return null;
        }
        String tenantCode = sysEqu.getTenantCode();
        List<SysGroup> groups = baseMapper.selectList(Wrappers.<SysGroup>lambdaQuery().eq(SysGroup::getTenantCode,tenantCode)
                                                                                        .eq(SysGroup::getDisabled,0));
        return groups;
    }

    @Override
    public IPage<SysGroup> getList(String inParam) {
        String userId = RequestHeaderUtils.getUserId(request);
        JSONObject object = JSONObject.parseObject(inParam);
        String tenantCode = object.getString("tenantCode");
        String groupName = object.getString("groupName");
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("userId",userId);
//        LambdaQueryWrapper<SysEqu> qw = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(tenantCode)) {
            paramMap.put("tenantCode",tenantCode);
        }
        if (StringUtils.isNotEmpty(groupName)) {
            paramMap.put("groupName",groupName);
        }

        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPage();
        Integer pageSize = pageDomain.getPageSize();
        Page<SysGroup> page = new Page<>(pageNum, pageSize);
        IPage<SysGroup> iPage = baseMapper.queryByPage(page, paramMap);
        return iPage;
    }

    @Override
    public String add(SysGroup sysGroup) throws Exception {
        String userId = RequestHeaderUtils.getUserId(request);
        String tenantCode = sysGroup.getTenantCode();
        String groupName = sysGroup.getGroupName();
        if(StringUtils.isEmpty(tenantCode) || StringUtils.isEmpty(groupName)){
            throw new Exception("参数不能为空");
        }
        //查询同一个项目下群组名称是否重复
        List<SysGroup> groups = baseMapper.selectList(Wrappers.<SysGroup>lambdaQuery().eq(SysGroup::getTenantCode,tenantCode)
                                                        .eq(SysGroup::getGroupName,groupName)
                                                        .eq(SysGroup::getDisabled,0));
        if(groups!=null && groups.size()>0){
            throw new Exception("群组名称重复");
        }

        sysGroup.setCreateId(userId);
        sysGroup.setCreateTime(new Date());
        sysGroup.setUpdateId(userId);
        sysGroup.setUpdateTime(new Date());
        sysGroup.setGroupType(0);
        baseMapper.insert(sysGroup);
        return "操作成功";
    }

    @Override
    public String update(Map<String, Object> param) throws Exception {
        String userId = RequestHeaderUtils.getUserId(request);
        String id = MapUtils.getString(param,"id");
        String groupName = MapUtils.getString(param,"groupName");
        String userIdStr = MapUtils.getString(param,"userIds");
        if(StringUtils.isEmpty(id) || StringUtils.isEmpty(groupName)){
            throw new Exception("参数不能为空");
        }
        SysGroup sysGroup = baseMapper.selectById(id);
        //更新sys_group表
        sysGroup.setGroupName(groupName);
        sysGroup.setUpdateTime(new Date());
        sysGroup.setUpdateId(userId);
        baseMapper.updateById(sysGroup);
        //先删除sys_user_group表，再插入新数据
        sysUserGroupService.remove(Wrappers.<SysUserGroup>lambdaQuery().eq(SysUserGroup::getGroupId,id));
        String[] userIds = userIdStr.split(",");
        for(int i=0;i<userIds.length;i++){
            SysUserGroup sysUserGroup = new SysUserGroup();
            sysUserGroup.setUserId(userIds[i]);
            sysUserGroup.setGroupId(id);
            sysUserGroup.setSort(i+1);
            sysUserGroup.setCreateId(userId);
            sysUserGroup.setCreateTime(new Date());
            sysUserGroup.setUpdateId(userId);
            sysUserGroup.setUpdateTime(new Date());
            sysUserGroupService.save(sysUserGroup);
        }



        return "操作成功";
    }

    @Override
    public String delete(String id) throws Exception {
        String userId = RequestHeaderUtils.getUserId(request);
        SysGroup sysGroup = baseMapper.selectById(id);
        if(sysGroup==null || StringUtils.isEmpty(sysGroup.getId())){
            throw new Exception("组不存在");
        }
        //查询是否绑定人员，若已绑定人员则不能进行删除
        List<SysUserGroup> sysUserGroups = sysUserGroupService.list(Wrappers.<SysUserGroup>lambdaQuery().eq(SysUserGroup::getGroupId,sysGroup.getId()).eq(SysUserGroup::getDisabled,0));
        if(sysUserGroups!=null && sysUserGroups.size()>0 && StringUtils.isNotEmpty(sysUserGroups.get(0).getUserId())){
            throw new Exception("已绑定人员，不能删除");
        }
        //删除
        sysGroup.setDisabled(1);
        sysGroup.setUpdateId(userId);
        sysGroup.setUpdateTime(new Date());
        baseMapper.updateById(sysGroup);
        return "操作成功";

    }
}
